package cc.vv.party.web;


import cc.vv.party.beans.model.Permission
import cc.vv.party.beans.vo.PermissionVO
import cc.vv.party.beans.vo.RoleVO
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import cc.vv.party.common.base.BaseController;
import cc.vv.party.common.ext.wrapper
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.common.wrapper.ResponseEntityWrapper
import cc.vv.party.service.PermissionService
import com.baomidou.mybatisplus.mapper.EntityWrapper
import com.baomidou.mybatisplus.plugins.Page
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author Gyb
 * @since 2018-10-13
 */
@RestController
@RequestMapping("/web/permission")
@Api(value = "权限资源", tags = ["权限资源服务端API"], description = "权限资源服务端API-服务端权限资源相关接口")
class PermissionController : BaseController() {

    @Autowired
    lateinit var permissionService: PermissionService

    @ApiOperation("权限树形结构列表")
    @GetMapping("/tree-list")
    fun treeList(): ResponseEntityWrapper<List<PermissionVO>> {
        val permissionList = permissionService.selectList(EntityWrapper<Permission>()).transferEntries<PermissionVO>()
        val map = permissionList.associateBy { it.id!! }
        val allChildrenList = permissionList.filter { it.parentId != "00" }.toList()
        val rootMap = map.filter { it.value.parentId == "00" }
        for (node in allChildrenList) {
            val rootNode = rootMap[node.parentId]
            if (rootNode != null) {
                if (rootNode.children == null) {
                    rootNode.children = mutableListOf()
                }
                rootNode.children!!.add(node)
            } else {
                val parent = map[node.parentId] ?: continue
                if (parent.children == null) {
                    parent.children = mutableListOf()
                }
                parent.children!!.add(node)
            }
        }
        return success(rootMap.values.toList())
    }

    @ApiOperation("权限列表")
    @GetMapping("/list")
    fun list(@RequestParam page: Int, @RequestParam pageSize: Int): ResponseEntityWrapper<PageWrapper<PermissionVO>> {
        return success(permissionService.selectPage(Page(page, pageSize)).wrapper())
    }
}
